//
//  Service_HomeMaking_Detail.m
//  MIT-AffordSuperMarket
//
//  Created by apple on 16/1/5.
//  Copyright © 2016年 河南大实惠电子商务有限公司. All rights reserved.
//
#import <JavaScriptCore/JavaScriptCore.h>

#import "Service_HomeMaking_Detail.h"
//controller
#import "SureOrderController.h"
#import "Login_Controller.h"
//untils
#import "UIColor+Hex.h"
#import "UIImage+ColorToImage.h"
#import "AppDelegate.h"
#import "NSString+Conversion.h"
#import "RDVTabBarController.h"
#import "MTA.h"
#import "Global.h"
#import "MBProgressHUD.h"
#import "ManagerGlobeUntil.h"
@interface Service_HomeMaking_Detail ()<UIWebViewDelegate>
@property(nonatomic,strong)UITableView *tableView;
@property (nonatomic, strong) UIWebView *webView;
@property (nonatomic, strong) JSContext *jsContext;
@property (nonatomic,strong)NSMutableDictionary *dicData;
@end

@implementation Service_HomeMaking_Detail

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor=[UIColor whiteColor];
    self.title =_topTitle;
    [self addBackNavItem];
    [self setUpSubView];
    self.jsContext = [[JSContext alloc] init];
    _dicData=[[NSMutableDictionary alloc]init];
    [[ManagerGlobeUntil sharedManager]showHUDWithMsg:@"加载中..."inView:self.view];
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self setWebViewData];
    AppDelegate *appDelegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
    [appDelegate.tabBarController setTabBarHidden:YES animated:NO];
}
-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    AppDelegate *appDelegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
    [appDelegate.tabBarController setTabBarHidden:NO animated:YES];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [MTA trackPageViewBegin:@"家政服务"];
}
- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [MTA trackPageViewEnd:@"家政服务"];
}

#pragma mark--获取WEB数据
-(void)setWebViewData
{
    NSString *URLStr =@"";
    if ([self.topTitle isEqualToString:@"日常保洁"]) {
        URLStr = [NSString stringWithFormat:@"%@ser/order/daily",baseServerUrl];
    }else{
        URLStr = [NSString stringWithFormat:@"%@ser/order/depth",baseServerUrl];
    }
        NSURL  *url =[[NSURL alloc]initWithString:URLStr];
        NSURLRequest *request = [NSURLRequest requestWithURL:url];
        [_webView loadRequest:request];
    
}
#pragma mark - UIWebViewDelegate

- (void)webViewDidFinishLoad:(UIWebView *)webView {
     [[ManagerGlobeUntil sharedManager] hideHUDFromeView:self.view];
    self.jsContext = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    [_webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.style.webkitUserSelect='none';"];
    [_webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.style.webkitTouchCallout='none';"];
    [webView stringByEvaluatingJavaScriptFromString:@"document.body.style.zoom=0.34"];
    self.jsContext.exceptionHandler = ^(JSContext *context, JSValue *exceptionValue) {
        context.exception = exceptionValue;
        NSLog(@"异常信息：%@", exceptionValue);
    };
}

#pragma mark --获取选中按钮数据
-(void)getDataWithJS
{
    [_dicData removeAllObjects];
    NSString * serviceDetail=[self.webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"getItem()"]];
    NSString *requestTmp = [NSString stringWithString:serviceDetail];
    
    NSData *resData = [[NSData alloc] initWithData:[requestTmp dataUsingEncoding:NSUTF8StringEncoding]];
      [_dicData addEntriesFromDictionary:[NSJSONSerialization JSONObjectWithData:resData options:NSJSONReadingMutableLeaves error:nil]];

}
#pragma mark-- buttonClick
-(void)appointmentClick
{
    [self getDataWithJS];
    XiaoQuAndStoreInfoModel *model =[[ManagerGlobeUntil sharedManager] getxiaoQuAndStoreInfo];
    if ([ManagerGlobeUntil sharedManager].transactionLogin) {
         if (model.storeID.integerValue != kDaShiHuiStoreID) {
        
        SureOrderController *sureOrderVC = [[SureOrderController alloc]init];
         sureOrderVC.homeMakeType =[self.topTitle isEqualToString:@"日常保洁"]?@"1":@"2";
        NSDictionary *dataDic = nil;
        if ([self.topTitle isEqualToString:@"日常保洁"]) {
          dataDic = @{@"STOREID":@"",@"SERVICESID":@"",@"MARKETPRICE":@"",@"SELLPRICE":[_dicData objectForKey:@"SELLPRICE"],@"TITLE":[_dicData objectForKey:@"TITLE"],@"COUNT":[_dicData objectForKey:@"COUNT"],@"HOUR":[_dicData objectForKey:@"HOUR"]};
        }else{
            dataDic = @{@"STOREID":@"",@"SERVICESID":@"",@"MARKETPRICE":@"",@"SELLPRICE":[_dicData objectForKey:@"SELLPRICE"],@"TITLE":[_dicData objectForKey:@"TITLE"],@"COUNT":[_dicData objectForKey:@"COUNT"],@"HOUR":@""};
        }
        sureOrderVC.orderType = kserviceSureorder;
        [sureOrderVC.serviceDataSource addObject:dataDic];
       
        
        [self.navigationController pushViewController:sureOrderVC animated:YES];
      } else {//大实惠总部店不可以下单
             UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"" message:@"您所在的小区暂未开通服务，敬请期待！" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles: nil];
             [alertView show];
         }
             
    } else {
        Login_Controller *loginVC = [[Login_Controller alloc]init];
        loginVC.supperControllerType = kServiceDetailPushtoLogin_ControllerSupperController;
        UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:loginVC];
        [self presentViewController:nav animated:YES completion:nil];
    }
    
}

-(void)backBtnAction:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}
#pragma mark--初始化控件
-(void)setUpSubView
{
    //初始化webView
    _webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0,VIEW_WIDTH , VIEW_HEIGHT-64-49)];
    _webView.scalesPageToFit = YES;
    _webView.delegate = self;
    _webView.backgroundColor=[UIColor whiteColor];
    _webView.scalesPageToFit = NO;
    [self.view addSubview:_webView];
    
    //底部按钮
    UIButton *appointment=[UIButton buttonWithType:UIButtonTypeCustom];
    appointment.frame=CGRectMake(15,  CGRectGetMaxY(self.webView.frame)+3, VIEW_WIDTH-30, 40);
    [appointment setTitle:@"立即预约" forState:UIControlStateNormal];
    appointment.titleLabel.font=[UIFont systemFontOfSize:15];
    UIImage *appointmentsImage = [UIImage createImageWithColor:[UIColor colorWithHexString:@"#c52720"]
                                                         frame:CGRectMake(0, 0, CGRectGetWidth(appointment.bounds), CGRectGetHeight(appointment.bounds))];
    [appointment setBackgroundImage:appointmentsImage forState:UIControlStateNormal];
    [appointment addTarget:self action:@selector(appointmentClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:appointment];
    [appointment.layer setMasksToBounds:YES];
    [appointment.layer setCornerRadius:3.0];
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
{
    return NO;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
